﻿using System.Collections.Generic;
using System.Linq;
using Game2DFramework;
using Game2DFramework.Extensions;
using MechGame.Game.Leveling;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MechGame.Game.Particles
{
    class ProjectileManager : GameObject
    {
        private Level _level;
        private readonly Texture2D _projectileTexture;
        private readonly Texture2D _rocketTexture;
        private readonly List<Projectile> _projectiles; 

        public ProjectileManager(Game2D game) : base(game)
        {
            _projectileTexture = game.Content.Load<Texture2D>("Textures/projectile");
            _rocketTexture = game.Content.Load<Texture2D>("Textures/rocket");
            _projectiles = new List<Projectile>();
            Game.GlobalObjectChanged += OnGlobalObjectChanged;
        }

        private void OnGlobalObjectChanged(string name, GameObject oldValue, GameObject newValue)
        {
            if (name == "Level") _level = (Level) newValue;
        }

        public void AddProjectile(Vector2 position, float speed, Vector2 direction, int damage)
        {
            _projectiles.Add(new Projectile(Game, position, speed, direction, damage) { Texture = _projectileTexture });
        }

        public void AddRocketProjectile(Vector2 position, float speed, Vector2 direction, int damage)
        {
            _projectiles.Add(new RocketProjectile(Game, position, speed, direction, damage) { Texture = _rocketTexture });
        }

        public bool TryGetProjetileCollidingWith(Rectangle bounds, out Projectile projectile)
        {
            projectile = _projectiles.FirstOrDefault(p => !p.Deleted && bounds.Contains(p.Position.ToPoint()));
            return projectile != null;
        }

        public void Update(float elapsedTime)
        {
            _projectiles.RemoveAll(p => p.ReadyToBeRemoved);

            foreach (var projectile in _projectiles)
            {
                projectile.Update(elapsedTime);
                GameObject gameObjectHit;
                if (_level.TryGetCollidingObject(projectile.Bounds, out gameObjectHit))
                {
                    projectile.OnCollide(gameObjectHit);
                }
            }
        }

        public void Draw()
        {
            _projectiles.ForEach(p => p.Draw());
        }
    }
}
